package com.itheima.utils;

import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.itheima.mode_test.User;

/**
 * 本地缓存淘汰策略 LRU
 * 比ConcurrentHashMap效率高, 可以释放内存
 */
@Component
public class LocalCache {

    private Cache<String, User> localCache = null;

    @PostConstruct
    private void init(){
        localCache = CacheBuilder.newBuilder()
                // 本地容器的初始容量
                .initialCapacity(10)
                // 本地缓存的最大容量
                .maximumSize(500)
                // 设置写缓存后多少秒后过期
                .expireAfterWrite(60, TimeUnit.SECONDS).build();

    }

    public void setLocalCache(String key, User user){
        localCache.put(key,user);
    }

    public User getLocalCache(String key){
        return localCache.getIfPresent(key);
    }
}
